package com.nageoffer.shortlink.project.toolkit;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;

import static com.nageoffer.shortlink.project.common.constant.ShortLinkConstant.DEFAULT_CACHE_VALID_TIME;

/**
 * 短链接工具类
 */
public class LinkUtil {
    /**
     * 获取短链接缓存有效期时间
     *
     * @param validTime 有效期时间
     * @return 有效期时间戳
     */
    public static long getLinkCacheValidTime(Date validTime) {
        return Optional.ofNullable(validTime)
                //在validTime不为null时，使用DateUtil.between计算当前时间和validTime之间的时间差，并将其转换成毫秒，从而得到缓存的有效时间。
                .map(each -> DateUtil.between(new Date(), each, DateUnit.MS))
                .orElse(DEFAULT_CACHE_VALID_TIME);
    }

    public static long getLinkCacheValidTime(LocalDateTime validTime) {
        return Optional.ofNullable(validTime)
                .map(each -> Duration.between(LocalDateTime.now(), each).toMillis())
                .orElse(DEFAULT_CACHE_VALID_TIME);
    }

    /**
     * 获取实际IP
     *
     * @param httpServletRequest 请求
     * @return IP
     */
    public static String getActualIp(HttpServletRequest httpServletRequest) {
        String realIp = httpServletRequest.getHeader("X-Forwarded-For");
        String unknown = "unknown";

        if (realIp == null || realIp.isEmpty() || unknown.equalsIgnoreCase(realIp)) {
            realIp = httpServletRequest.getHeader("Proxy-Client-IP");
        }
        if (realIp == null || realIp.isEmpty() || unknown.equalsIgnoreCase(realIp)) {
            realIp = httpServletRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (realIp == null || realIp.isEmpty() || unknown.equalsIgnoreCase(realIp)) {
            realIp = httpServletRequest.getHeader("HTTP_CLIENT_IP");
        }
        if (realIp == null || realIp.isEmpty() || unknown.equalsIgnoreCase(realIp)) {
            realIp = httpServletRequest.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (realIp == null || realIp.isEmpty() || unknown.equalsIgnoreCase(realIp)) {
            realIp = httpServletRequest.getRemoteAddr();
        }

        return realIp;
    }

    /**
     * 获取操作系统类型
     *
     * @param httpServletRequest 请求
     * @return 操作系统
     */
    public static String getOs(HttpServletRequest httpServletRequest) {
        String userAgent = httpServletRequest.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("windows")) {
            return "Windows";
        } else if (userAgent.toLowerCase().contains("mac")) {
            return "Mac OS";
        } else if (userAgent.toLowerCase().contains("linux")) {
            return "Linux";
        } else if (userAgent.toLowerCase().contains("unix")) {
            return "Unix";
        } else if (userAgent.toLowerCase().contains("android")) {
            return "Android";
        } else if (userAgent.toLowerCase().contains("iphone")) {
            return "iOS";
        } else {
            return "Unknown";
        }
    }

    /**
     * 获取用户访问浏览器
     * @param httpServletRequest 请求
     * @return 访问浏览器
     */
    public static String getBrowser(HttpServletRequest httpServletRequest) {
        String userAgent = httpServletRequest.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("edg")) {
            return "Microsoft Edge";
        } else if (userAgent.toLowerCase().contains("chrome")) {
            return "Google Chrome";
        } else if (userAgent.toLowerCase().contains("firefox")) {
            return "Mozilla Firefox";
        } else if (userAgent.toLowerCase().contains("safari")) {
            return "Apple Safari";
        } else if (userAgent.toLowerCase().contains("opera")) {
            return "Opera";
        } else if (userAgent.toLowerCase().contains("msie") || userAgent.toLowerCase().contains("trident")) {
            return "Internet Explorer";
        } else {
            return "Unknown";
        }
    }

    /**
     * 获取用户访问设备
     *
     * @param httpServletRequest 请求
     * @return 访问设备
     */
    public static String getDevice(HttpServletRequest httpServletRequest) {
        String userAgent = httpServletRequest.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("mobile")) {
            return "Mobile";
        }
        return "PC";
    }

    /**
     * 获取用户访问网络
     * @param httpServletRequest 请求
     * @return 访问网络
     */
    public static String getNetwork(HttpServletRequest httpServletRequest) {
        String actualIp = getActualIp(httpServletRequest);
        // 这里简单判断IP地址范围，您可能需要更复杂的逻辑
        // 例如，通过调用IP地址库或调用第三方服务来判断网络类型
        if(actualIp.equals("127.0.0.1"))return "Localhost";
        return actualIp.startsWith("192.168.") || actualIp.startsWith("10.") || isWiFiDevice(actualIp)? "WIFI" : "Mobile";
    }
    private static boolean isWiFiDevice(String actualIp) {
        for (int i = 16; i <=31 ; i++) {
            if (actualIp.startsWith("172."+i)){
                return true;
            }
        }
        return false;
    }
}
